package com.ustb.mainweb;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class TestFrame extends JFrame {
    private Timer timer;
    private JLabel stimulusLabel;
    private JLabel responseTimeLabel;
    private JLabel instructionsLabel;
    private long startTime;
    private long responseTime;
    private int correctResponses = 0;
    private int totalStimuli = 0;

    public TestFrame() {
        setTitle("AX-CPT Test - In Progress");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        setLocationRelativeTo(null);
        initUI();
    }

    private void initUI() {
        setLayout(new BorderLayout());

        stimulusLabel = new JLabel("Press any key to start", SwingConstants.CENTER);
        add(stimulusLabel, BorderLayout.CENTER);

        responseTimeLabel = new JLabel("Response Time: N/A", SwingConstants.CENTER);
        add(responseTimeLabel, BorderLayout.SOUTH);

        instructionsLabel = new JLabel("Instructions: Respond as quickly as possible to the target stimulus.", SwingConstants.CENTER);
        add(instructionsLabel, BorderLayout.NORTH);

        timer = new Timer(1000, e -> generateStimulus());
        timer.start();

        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                responseTime = System.currentTimeMillis() - startTime;
                if (isCorrectResponse()) {
                    correctResponses++;
                }
                totalStimuli++;
                recordResponse();
                generateStimulus();
            }
        });

        pack();
        setVisible(true);
    }

    private void generateStimulus() {
        Random rand = new Random();
        int stimulus = rand.nextInt(9) + 1; // 1-9数字
        stimulusLabel.setText(String.valueOf(stimulus));
        startTime = System.currentTimeMillis();
    }

    private boolean isCorrectResponse() {
        // 假设目标刺激是数字5
        return Integer.parseInt(stimulusLabel.getText()) == 5;
    }

    private void recordResponse() {
        if (responseTime > 0) {
            responseTimeLabel.setText("Response Time: " + responseTime + " ms");
        }
    }

    public void stopTest() {
        timer.stop();
        JOptionPane.showMessageDialog(this, "Test Completed!\nCorrect Responses: " + correctResponses + "\nTotal Stimuli: " + totalStimuli + "\nAccuracy: " + ((double) correctResponses / totalStimuli * 100) + "%");
        dispose();
    }
}